import serial import serial.tools.list_ports import requests def find_serial_port(vendor_id, product_id): """Find and return the serial port for the given vendor ID and product ID.""" ports = serial.tools.list_ports.comports() for port in ports: if port.vid == vendor_id and port.pid == product_id: return port.device return None def send_binary_data(ser, data): """Send binary data over the serial connection.""" ser.write(data) # Send the binary data print("Sent binary data.") def download_image(url): """Download an image from the URL and return its byte array.""" try: response = requests.get(url) response.raise_for_status() # Ensure the request was successful return response.content # Return the binary data of the image except requests.exceptions.RequestException as e: print(f"Error downloading the image: {e}") return None # Define vendor and product IDs vendor_id = 0x0483 # STMicroelectronics vendor ID product_id = 0x5740 # STMicroelectronics Virtual COM Port product ID # List of image URLs (used for selection) image_urls = { '1': "https://download.rechargegrid.in/download/welcome_compress.bin", '2': "https://download.rechargegrid.in/download/qr_compress.bin", '3': "https://download.rechargegrid.in/download/success_compress.bin", '4': "https://download.rechargegrid.in/download/fail_compress.bin", '5': "https://download.rechargegrid.in/download/pending_compress.bin" } # Find the correct serial port device_path = find_serial_port(vendor_id, product_id) if device_path: print(f"Found device at {device_path}") try: # Open serial connection ser = serial.Serial(device_path, 115200, timeout=1) print(f"Connected to {device_path}") # Show available image options to the user print("Select an image to send:") for key, value in image_urls.items(): print(f"{key}: {value}") # Get user input for image selection choice = input("Enter the number of the image you want to send: ") if choice in image_urls: # Download the image print(f"Downloading image from: {image_urls[choice]}") binary_data = download_image(image_urls[choice]) if binary_data: # Send the image as binary data over the serial port send_binary_data(ser, binary_data) else: print("Failed to download the image.") else: print("Invalid selection. Please choose a valid image number.") # Close the connection ser.close() except serial.SerialException as e: print(f"Error opening serial port: {e}") else: print("Device not found.")